<template>
  <div class="watchEffect">
    <h1>需求：水温达到50℃，或水位达到20cm，则联系服务器</h1>
    <h2 id="demo">水温：{{ temp }}</h2>
    <h2>水位：{{ height }}</h2>
    <button @click="changePrice" id="demo">水温+1</button>
    <button @click="changeSum">水位+10</button>
    <h1>姓名:{{reactivePerson.name}},年龄:{{reactivePerson.age}}</h1>
    <h1>姓名:{{refPerson.name}},年龄:{{refPerson.age}}</h1>
    <button @click="changeNameRE()">reactive修改名字</button>
    <button @click="changeNameRF()">ref修改名字</button>
    <button @click="changeAgeRE()">reactive修改年龄</button>
    <button @click="changeAgeRF()">ref修改年龄</button>
  </div>
</template>
<script lang="ts" setup>
import {reactive,ref, watch, watchEffect } from "vue";
// 数据
let temp = ref(0)
let height = ref(0)
let reactivePerson = reactive({name:"张三",age:15})
let refPerson = ref({name:"李四",age:17})
// 方法
function changePrice(){temp.value += 10}
function changeSum(){height.value += 1}
function changeNameRE(){reactivePerson.name += '~'}
function changeNameRF(){refPerson.value.name += '!'}
function changeAgeRE(){reactivePerson.age += 1}
function changeAgeRF(){refPerson.value.age += 10}
// 用watch实现,需要明确的指出要监视:temp,height
watch([temp,height],(value)=>{
    // 从value中获取最新的temp值,height值
    const [newTemp,newHeight] = value
    console.log(value);
    // 室温达到50°C,或水位达到20cm,立刻联系服务器
    if(newTemp >= 50 || newHeight >= 20){
        console.log('立刻联系服务器');
    }
},{deep:true})
// 用watchEffect实现,不用
const stopWatch = watchEffect(()=>{
   // 室温达到50°C,或水位达到20cm,立刻联系服务器
   if(temp.value >=50 || height.value >=20){
    console.log(document.getElementById('demo')?.innerText)
    console.log('联系服务器')
   }
   // 水温达到100，或水位达到50，取消监视
    if(temp.value === 100 || height.value === 50){
      console.log('取消监视')
      stopWatch()
    }
})
// 
// 用watch实现监听,如果是对象需要()=>,如果是基本类型不用,直接用[]包起来
watch([()=>reactivePerson.name,refPerson],(value)=>{
    console.log(value,'value')
},{deep:true})
</script>
<style scoped>
.watchEffect {
  width: 80vw;
  height: 80vh;
  border: 1px solid red;
}
</style>
